package com.nsgf.library.ui.page.warehouse;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.ClockInBean;
import com.nsgf.library.data.bean.WareHouseBean;
import com.nsgf.library.databinding.ActivityNsgfHomeWareHouseBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.WareHouseListAdapter;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * 仓库
 */
public class WareHouseListActivity extends BaseActivity {
    private CheckWorkAttendanceState mStates;

    private WareHouseListAdapter mAdapter;
    ActivityNsgfHomeWareHouseBinding mBinding;

    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(CheckWorkAttendanceState.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new WareHouseListAdapter(this);

        return new DataBindingConfig(R.layout.activity_nsgf_home_ware_house, BR.vm, mStates)
                .addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityNsgfHomeWareHouseBinding) getBinding();
        mBinding.titlebar.titleBarClear.setImageResource(R.drawable.ic_home_video_sort);
        mBinding.titlebar.titleBarClear.setVisibility(View.VISIBLE);
        mStates.titleBar.set("防汛仓库");

        String url = "file:///android_asset/roadLine/index.html";
        WebSettings mWebSettings = mBinding.webView.getWebView().getSettings();
        mWebSettings.setJavaScriptEnabled(true);//设置支持javaScript
        mBinding.webView.loadUrl(url);
        // 当页面加载完成后调用JavaScript方法
        mBinding.webView.getWebView().setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mAccountRequester.getStore("");
            }
        });
        mBinding.webView.getWebView().addJavascriptInterface(new WebViewInterface(), "android");

        mAccountRequester.getWareHouseResult().observe(WareHouseListActivity.this, responseStatusDataResult -> {

            if (200 == responseStatusDataResult.getResponseCode()) {
                mStates.list.set(responseStatusDataResult.getData());
                if (mStates.list.get().size() == 0) {
                    mStates.mNodata.set(View.VISIBLE);
                } else
                    mStates.mNodata.set(View.GONE);
                JSONArray initArray = new JSONArray();
                JSONObject params = null;
                for (WareHouseBean dataBean : responseStatusDataResult.getData()) {

                    String[] points = dataBean.getCoordinates().split(",");

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("lat", points[1]);
                    jsonObject.put("lon", points[0]);
                    jsonObject.put("positionName", dataBean.getStoreName());
                    jsonObject.put("status", 7);
                    jsonObject.put("id", dataBean.getId());
                    initArray.add(jsonObject);
                    if (null == params)
                        params = jsonObject;
                }
                callJavaScriptDrawInitPintFunction(params, initArray);
            } else {
                showToast(responseStatusDataResult.getMsg());
            }
        });

        mAdapter.setOnItemClickListener(new BaseDataBindingAdapter.OnItemClickListener<WareHouseBean>() {
            @Override
            public void onItemClick(int viewId, WareHouseBean item, int position) {

                startActivity(new Intent()
                        .putExtra("bean", mAdapter.getCurrentList().get(position))
                        .setClass(WareHouseListActivity.this,
                                WareHouseInfoActivity.class));
            }
        });
    }

    private void callJavaScriptDrawInitPintFunction(JSONObject object, JSONArray list) {
        mBinding.webView.getWebView().evaluateJavascript("drawInitPintProject(" + list + ");", null);

    }

    public static class CheckWorkAttendanceState extends StateHolder {

        public final State<Integer> mWayMap = new State<>(View.INVISIBLE);
        public final State<Integer> mWayList = new State<>(View.VISIBLE);
        public final State<Integer> mNodata = new State<>(View.GONE);


        public final State<List<WareHouseBean>> list = new State<>(new ArrayList<>());

        public final State<Boolean> loadingVisible = new State<>(false);

    }

    private boolean mapList = true;//false 地图 true 列表

    @Override
    protected void onClickSecurity(View v) {
        super.onClickSecurity(v);
        int id = v.getId();
        if (id == R.id.title_bar_clear) {
            mapList = !mapList;
            mBinding.titlebar.titleBarClear.setImageResource(mapList ? R.drawable.ic_home_video_map : R.drawable.ic_home_video_sort);
            if (mapList) {
                mStates.mWayList.set(View.VISIBLE);
                mStates.mWayMap.set(View.INVISIBLE);
            } else {
                mStates.mWayList.set(View.GONE);
                mStates.mWayMap.set(View.VISIBLE);
            }
        }
    }


    public class ClickProxy {

        public void search() {
            mAccountRequester.getStore(mStates.searchContent.get());
        }
    }

    /**
     * Js调用的JavascriptInterface
     */
    public class WebViewInterface {

        @JavascriptInterface
        public void openDetails(String src) {
            Gson gson = new Gson();
            ClockInBean.DataBean.LateAndEarlyListBean info = gson.fromJson(src, ClockInBean.DataBean.LateAndEarlyListBean.class);
            for (WareHouseBean houseBean : mAdapter.getCurrentList()) {
                if (houseBean.getId().equals(info.getId())) {
                    startActivity(new Intent()
                            .putExtra("bean", houseBean)
                            .setClass(WareHouseListActivity.this,
                                    WareHouseInfoActivity.class));
                    return;
                }
            }
        }
    }

}
